package com.cskaoyan.day20;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class PasswordTest {

    public static void main(String[] args) throws InterruptedException {
        LogThread logThread = new LogThread();
        logThread.setDaemon(true);
        logThread.start();

        TimeUnit.SECONDS.sleep(2);
    }
}

class Mythread extends Thread {
    static boolean flag = false;
    static StringBuffer sb = new StringBuffer();
    static int password = (int) (Math.random() * 1000);

    static {
        System.out.println("密码生成成功：" + password);
    }

    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < 1000; i++) {
            if (i == password) {
                String format = sdf.format(new Date());
                sb.append("[" + format + "]" + "尝试破解密码：" + i + ",   密码正确，破解成功！\n");
                flag = true;
                System.out.println("破解成功！开始写入日志文件...");
                return;
            }
            String format = sdf.format(new Date());
            sb.append("[" + format + "]" + "尝试破解密码：" + i + ",   密码错误，破解失败！\n");
        }
    }
}

class LogThread extends Thread {

    @Override
    public void run() {

        Mythread mythread = new Mythread();
        mythread.start();
        try {
            mythread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Logpassword.txt"))) {
            out.write(Mythread.sb.toString().getBytes());
            System.out.println("日志已生成！");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
